import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { useDataModelStore } from './dataModelStore'

export const useDataCleaningStore = defineStore('dataCleaning', () => {
  // 数据源
  const dataSources = ref([
    {
      id: 'sample_raw_data',
      name: '示例原始数据',
      type: 'excel',
      rowCount: 12,
      data: [
        { id: 1, name: '张三', age: 25, department: '技术部', salary: 8000, city: '北京', hire_date: '2024-01-15', email: 'zhang@example.com' },
        { id: 2, name: '李四', age: null, department: '销售部', salary: 6500, city: '上海', hire_date: '2024-01-16', email: 'li@example.com' },
        { id: 3, name: '王五', age: 28, department: '技术部', salary: '', city: '深圳', hire_date: '2024-01-17', email: 'wang@example.com' },
        { id: 4, name: '', age: 35, department: '市场部', salary: 7200, city: '广州', hire_date: '2024-01-18', email: 'zhao@example.com' },
        { id: 5, name: '钱七', age: 26, department: '技术部', salary: 8800, city: '杭州', hire_date: '2024-01-19', email: '' },
        { id: 6, name: '孙八', age: 32, department: '销售部', salary: 7000, city: '成都', hire_date: '2024-01-20', email: 'sun@example.com' },
        { id: 7, name: '周九', age: 29, department: '市场部', salary: 6800, city: '武汉', hire_date: '2024-01-21', email: 'zhou@example.com' },
        { id: 8, name: '吴十', age: 27, department: '技术部', salary: 9200, city: '西安', hire_date: '2024-01-22', email: 'wu@example.com' },
        // 重复数据
        { id: 9, name: '张三', age: 25, department: '技术部', salary: 8000, city: '北京', hire_date: '2024-01-15', email: 'zhang@example.com' },
        { id: 10, name: '李四', age: 30, department: '销售部', salary: 6500, city: '上海', hire_date: '2024-01-16', email: 'li@example.com' },
        // 异常数据
        { id: 11, name: '测试用户', age: 'abc', department: '技术部', salary: -1000, city: '北京', hire_date: 'invalid-date', email: 'invalid-email' },
        { id: 12, name: '   空格用户   ', age: 999, department: '  技术部  ', salary: 999999, city: '   北京   ', hire_date: '2024-01-23', email: '  test@example.com  ' }
      ],
      columns: [
        { field: 'id', name: 'ID', dataType: 'number' },
        { field: 'name', name: '姓名', dataType: 'text' },
        { field: 'age', name: '年龄', dataType: 'number' },
        { field: 'department', name: '部门', dataType: 'text' },
        { field: 'salary', name: '薪资', dataType: 'currency' },
        { field: 'city', name: '城市', dataType: 'text' },
        { field: 'hire_date', name: '入职日期', dataType: 'date' },
        { field: 'email', name: '邮箱', dataType: 'text' }
      ]
    }
  ])

  // 清洗历史记录
  const cleaningHistory = ref([])

  // 清洗规则
  const cleaningRules = ref([
    {
      id: 'remove_empty_rows',
      name: '删除空行',
      description: '删除所有字段都为空的行',
      enabled: true
    },
    {
      id: 'remove_duplicates',
      name: '去除重复',
      description: '删除完全重复的数据行',
      enabled: true
    },
    {
      id: 'trim_whitespace',
      name: '去除空格',
      description: '去除文本字段首尾空格',
      enabled: true
    },
    {
      id: 'standardize_case',
      name: '标准化大小写',
      description: '统一文本字段的大小写',
      enabled: false
    },
    {
      id: 'validate_email',
      name: '验证邮箱格式',
      description: '检查邮箱地址格式是否正确',
      enabled: true
    },
    {
      id: 'validate_date',
      name: '验证日期格式',
      description: '检查日期格式是否正确',
      enabled: true
    }
  ])

  // 数据质量指标
  const qualityMetrics = ref({
    completeness: 0,
    consistency: 0,
    validity: 0,
    uniqueness: 0
  })

  // 计算属性
  const totalDataSources = computed(() => dataSources.value.length)
  const totalRows = computed(() => dataSources.value.reduce((sum, ds) => sum + ds.rowCount, 0))
  const cleanedDataSources = computed(() => dataSources.value.filter(ds => ds.cleaned))

  // 方法
  const addDataSource = (dataSource) => {
    const newDataSource = {
      id: Date.now().toString(),
      ...dataSource,
      cleaned: false,
      createdAt: new Date().toISOString()
    }
    dataSources.value.push(newDataSource)
    return newDataSource
  }

  const updateDataSource = (id, updates) => {
    const index = dataSources.value.findIndex(ds => ds.id === id)
    if (index !== -1) {
      dataSources.value[index] = {
        ...dataSources.value[index],
        ...updates
      }
    }
  }

  const removeDataSource = (id) => {
    const index = dataSources.value.findIndex(ds => ds.id === id)
    if (index !== -1) {
      dataSources.value.splice(index, 1)
    }
  }

  const addCleaningOperation = (operation) => {
    const newOperation = {
      id: Date.now().toString(),
      ...operation,
      timestamp: Date.now()
    }
    cleaningHistory.value.unshift(newOperation)
    
    // 限制历史记录数量
    if (cleaningHistory.value.length > 50) {
      cleaningHistory.value = cleaningHistory.value.slice(0, 50)
    }
    
    return newOperation
  }

  const undoOperation = (operationId) => {
    // 简化的撤销操作
    const index = cleaningHistory.value.findIndex(op => op.id === operationId)
    if (index !== -1) {
      cleaningHistory.value.splice(index, 1)
    }
  }

  const clearHistory = () => {
    cleaningHistory.value = []
  }

  // 数据清洗方法
  const removeEmptyRows = (dataSourceId) => {
    const dataSource = dataSources.value.find(ds => ds.id === dataSourceId)
    if (!dataSource) return

    const originalCount = dataSource.data.length
    dataSource.data = dataSource.data.filter(row => 
      Object.values(row).some(value => value != null && value !== '')
    )
    
    const removedCount = originalCount - dataSource.data.length
    dataSource.rowCount = dataSource.data.length

    addCleaningOperation({
      name: `删除空行 (${removedCount}行)`,
      type: 'remove_empty_rows',
      sourceId: dataSourceId,
      details: { removedCount }
    })

    return removedCount
  }

  const removeDuplicates = (dataSourceId) => {
    const dataSource = dataSources.value.find(ds => ds.id === dataSourceId)
    if (!dataSource) return

    const originalCount = dataSource.data.length
    const seen = new Set()
    
    dataSource.data = dataSource.data.filter(row => {
      const key = JSON.stringify(row)
      if (seen.has(key)) {
        return false
      }
      seen.add(key)
      return true
    })
    
    const removedCount = originalCount - dataSource.data.length
    dataSource.rowCount = dataSource.data.length

    addCleaningOperation({
      name: `去除重复 (${removedCount}行)`,
      type: 'remove_duplicates',
      sourceId: dataSourceId,
      details: { removedCount }
    })

    return removedCount
  }

  const trimWhitespace = (dataSourceId) => {
    const dataSource = dataSources.value.find(ds => ds.id === dataSourceId)
    if (!dataSource) return

    let trimmedCount = 0
    
    dataSource.data.forEach(row => {
      dataSource.columns.forEach(column => {
        if (column.dataType === 'text' && row[column.field]) {
          const original = row[column.field]
          const trimmed = String(original).trim()
          if (original !== trimmed) {
            row[column.field] = trimmed
            trimmedCount++
          }
        }
      })
    })

    addCleaningOperation({
      name: `去除空格 (${trimmedCount}个)`,
      type: 'trim_whitespace',
      sourceId: dataSourceId,
      details: { trimmedCount }
    })

    return trimmedCount
  }

  const validateData = (dataSourceId) => {
    const dataSource = dataSources.value.find(ds => ds.id === dataSourceId)
    if (!dataSource) return

    const issues = []
    
    dataSource.data.forEach((row, rowIndex) => {
      dataSource.columns.forEach(column => {
        const value = row[column.field]
        
        // 检查数据类型
        if (column.dataType === 'number' && value != null && value !== '' && isNaN(Number(value))) {
          issues.push({
            row: rowIndex + 1,
            column: column.name,
            issue: '数据类型不匹配',
            value: value
          })
        }
        
        // 检查邮箱格式
        if (column.field === 'email' && value && !isValidEmail(value.trim())) {
          issues.push({
            row: rowIndex + 1,
            column: column.name,
            issue: '邮箱格式无效',
            value: value
          })
        }
        
        // 检查日期格式
        if (column.dataType === 'date' && value && !isValidDate(value)) {
          issues.push({
            row: rowIndex + 1,
            column: column.name,
            issue: '日期格式无效',
            value: value
          })
        }
      })
    })

    return issues
  }

  const isValidEmail = (email) => {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
    return emailRegex.test(email)
  }

  const isValidDate = (dateString) => {
    const date = new Date(dateString)
    return date instanceof Date && !isNaN(date)
  }

  const calculateQualityMetrics = (dataSourceId) => {
    const dataSource = dataSources.value.find(ds => ds.id === dataSourceId)
    if (!dataSource) return

    const totalCells = dataSource.data.length * dataSource.columns.length
    let emptyCells = 0
    let invalidCells = 0
    
    // 计算完整性
    dataSource.data.forEach(row => {
      dataSource.columns.forEach(column => {
        const value = row[column.field]
        if (value == null || value === '') {
          emptyCells++
        }
        
        // 检查数据有效性
        if (column.dataType === 'number' && value != null && value !== '' && isNaN(Number(value))) {
          invalidCells++
        }
      })
    })

    const completeness = Math.round(((totalCells - emptyCells) / totalCells) * 100)
    const validity = Math.round(((totalCells - invalidCells) / totalCells) * 100)
    
    // 计算唯一性
    const duplicateRows = findDuplicateRows(dataSource.data)
    const uniqueness = Math.round(((dataSource.data.length - duplicateRows) / dataSource.data.length) * 100)

    qualityMetrics.value = {
      completeness,
      consistency: 95, // 简化计算
      validity,
      uniqueness
    }

    return qualityMetrics.value
  }

  const findDuplicateRows = (data) => {
    const seen = new Set()
    let duplicates = 0
    
    data.forEach(row => {
      const key = JSON.stringify(row)
      if (seen.has(key)) {
        duplicates++
      } else {
        seen.add(key)
      }
    })
    
    return duplicates
  }

  const applyCleaningRules = (dataSourceId, rules = null) => {
    const rulesToApply = rules || cleaningRules.value.filter(rule => rule.enabled)
    let totalOperations = 0
    
    rulesToApply.forEach(rule => {
      switch (rule.id) {
        case 'remove_empty_rows':
          totalOperations += removeEmptyRows(dataSourceId)
          break
        case 'remove_duplicates':
          totalOperations += removeDuplicates(dataSourceId)
          break
        case 'trim_whitespace':
          totalOperations += trimWhitespace(dataSourceId)
          break
      }
    })

    // 标记为已清洗
    updateDataSource(dataSourceId, { cleaned: true })
    
    return totalOperations
  }

  const saveToDataModel = (dataSource) => {
    const dataModelStore = useDataModelStore()
    
    // 转换为数据模型格式
    const modelDataSource = {
      name: `${dataSource.name} (已清洗)`,
      type: 'cleaned',
      description: '来自数据清洗模块的清洗数据',
      tables: [
        {
          name: dataSource.name.replace(/\s+/g, '_').toLowerCase(),
          description: `清洗后的${dataSource.name}`,
          rowCount: dataSource.data.length,
          fields: dataSource.columns.map(column => ({
            name: column.name,
            dataType: column.dataType,
            category: column.dataType === 'number' || column.dataType === 'currency' ? '度量值' : '维度',
            isPrimaryKey: column.field === 'id',
            isForeignKey: column.field.endsWith('_id') && column.field !== 'id',
            isCalculated: false
          }))
        }
      ]
    }
    
    // 添加到数据模型
    dataModelStore.addDataSource(modelDataSource)
    
    // 同时保存原始数据到数据模型store中
    // 这里可以扩展数据模型store来支持原始数据存储
    
    return modelDataSource
  }

  const exportCleanedData = (dataSourceId, format = 'json') => {
    const dataSource = dataSources.value.find(ds => ds.id === dataSourceId)
    if (!dataSource) return null

    switch (format) {
      case 'json':
        return JSON.stringify(dataSource.data, null, 2)
      case 'csv':
        return convertToCSV(dataSource.data, dataSource.columns)
      default:
        return dataSource.data
    }
  }

  const convertToCSV = (data, columns) => {
    const headers = columns.map(col => col.name).join(',')
    const rows = data.map(row => 
      columns.map(col => {
        const value = row[col.field]
        return value != null ? `"${value}"` : '""'
      }).join(',')
    )
    
    return [headers, ...rows].join('\n')
  }

  const getDataPreview = (dataSourceId, limit = 10) => {
    const dataSource = dataSources.value.find(ds => ds.id === dataSourceId)
    if (!dataSource) return null

    return {
      columns: dataSource.columns,
      data: dataSource.data.slice(0, limit),
      totalRows: dataSource.data.length
    }
  }

  return {
    // 状态
    dataSources,
    cleaningHistory,
    cleaningRules,
    qualityMetrics,
    
    // 计算属性
    totalDataSources,
    totalRows,
    cleanedDataSources,
    
    // 数据源管理
    addDataSource,
    updateDataSource,
    removeDataSource,
    
    // 清洗操作
    addCleaningOperation,
    undoOperation,
    clearHistory,
    
    // 清洗方法
    removeEmptyRows,
    removeDuplicates,
    trimWhitespace,
    validateData,
    calculateQualityMetrics,
    applyCleaningRules,
    
    // 数据导出
    saveToDataModel,
    exportCleanedData,
    getDataPreview
  }
})

